{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## python csv模块读取csv文件\n",
    "csv文件说明：\n",
    "“CSV”并不是一种单一的、定义明确的格式（尽管RFC 4180有一个被通常使用的定义）。因此在实践中，术语“CSV”泛指具有以下特征的任何文件：\n",
    "* 纯文本，使用某个字符集，比如ASCII、Unicode、EBCDIC或GB2312；\n",
    "* 由记录组成（典型的是每行一条记录）；\n",
    "* 每条记录被分隔符分隔为字段（典型分隔符有逗号、分号或制表符；有时分隔符可以包括可选的空格）；\n",
    "* 每条记录都有同样的字段序列。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. 读取csv文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import csv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'基本每股收益(元)': '0.8'}\n",
      "{'每股净资产(元)': '15.83'}\n",
      "{'每股经营活动产生的现金流量净额(元)': '-5.98'}\n",
      "{'主营业务收入(万元)': '8468000'}\n",
      "{'主营业务利润(万元)': '2241500'}\n",
      "{'营业利润(万元)': '2241500'}\n",
      "{'投资收益(万元)': '596300'}\n",
      "{'营业外收支净额(万元)': '-7400'}\n",
      "{'利润总额(万元)': '2234100'}\n",
      "{'净利润(万元)': '1758300'}\n",
      "{'净利润(扣除非经常性损益后)(万元)': '1751100'}\n",
      "{'经营活动产生的现金流量净额(万元)': '-11597200'}\n",
      "{'现金及现金等价物净增加额(万元)': '1916700'}\n",
      "{'总资产(万元)': '472352000'}\n",
      "{'流动资产(万元)': '--'}\n",
      "{'总负债(万元)': '434632700'}\n",
      "{'流动负债(万元)': '--'}\n",
      "{'股东权益不含少数股东权益(万元)': '37719300'}\n",
      "{'净资产收益率加权(%)': '5.17'}\n"
     ]
    }
   ],
   "source": [
    "# 使用reader函数获取数据\n",
    "with open('pa.csv','r',encoding='GB2312') as fp:\n",
    "    # reader是一个迭代器\n",
    "    reader = csv.reader(fp)\n",
    "    # 直接读取下一行,针对迭代器使用next函数\n",
    "    next(reader)\n",
    "    for x in reader:\n",
    "        try:\n",
    "            #读取最近一个季度的数据\n",
    "            name = x[0]\n",
    "            value = x[1]\n",
    "            print({name:value})\n",
    "        except:\n",
    "            pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "基本每股收益(元) : 0.8\n",
      "每股净资产(元) : 15.83\n",
      "每股经营活动产生的现金流量净额(元) : -5.98\n",
      "主营业务收入(万元) : 8468000\n",
      "主营业务利润(万元) : 2241500\n",
      "营业利润(万元) : 2241500\n",
      "投资收益(万元) : 596300\n",
      "营业外收支净额(万元) : -7400\n",
      "利润总额(万元) : 2234100\n",
      "净利润(万元) : 1758300\n",
      "净利润(扣除非经常性损益后)(万元) : 1751100\n",
      "经营活动产生的现金流量净额(万元) : -11597200\n",
      "现金及现金等价物净增加额(万元) : 1916700\n",
      "总资产(万元) : 472352000\n",
      "流动资产(万元) : --\n",
      "总负债(万元) : 434632700\n",
      "流动负债(万元) : --\n",
      "股东权益不含少数股东权益(万元) : 37719300\n",
      "净资产收益率加权(%) : 5.17\n",
      "\t\t : None\n",
      "\t\t : None\n",
      "\t\t : None\n",
      "\t\t : None\n",
      "\t\t : None\n",
      "\t\t : None\n",
      "\t\t : None\n",
      "\t\t : None\n",
      "\t\t : None\n",
      "\t\t : None\n",
      "\t\t : None\n",
      "\t\t : None\n",
      "\t\t : None\n",
      "\t\t : None\n",
      "\t\t : None\n",
      "\t\t : None\n",
      "\t\t : None\n",
      "\t\t : None\n"
     ]
    }
   ],
   "source": [
    "# 第二种方法：DictReader\n",
    "with open('pa.csv','r',encoding='gb2312') as fp:\n",
    "    dicreader=csv.DictReader(fp)\n",
    "    for d in dicreader:\n",
    "        print(d['报告日期'],':',d['2021-06-30'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2. 写入csv文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "#普通写入方式csv.writer\n",
    "header=['name','age','height']\n",
    "values=[\n",
    "    ('小名',18,170),\n",
    "    ('小李',19,186),\n",
    "    ('小刚',17,170),\n",
    "]\n",
    "'''\n",
    "encoding:设置写入文件的代码\n",
    "newline:默认参数为'\\n'，即每行写完之后加入一个空行。如果不想加空行，需要将参数设置成''空字符串\n",
    "'''\n",
    "with open('classroom.csv','w',encoding='utf-8',newline='') as fp:\n",
    "    writer=csv.writer(fp)\n",
    "    writer.writerow(header)\n",
    "    writer.writerows(values)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "#使用字典的方式写入csv文件\n",
    "header = ['name','age','height']\n",
    "values=[\n",
    "    {'name':'小名','age':18,'height':120},\n",
    "    {'name':'小李','age':19,'height':160},\n",
    "    {'name':'小张','age':15,'height':170}\n",
    "]\n",
    "with open('classroom1.csv','w',encoding='utf-8',newline='') as fp:\n",
    "    writer=csv.DictWriter(fp,header)\n",
    "    #需要手动写入表头\n",
    "    writer.writeheader()\n",
    "    writer.writerows(values)\n",
    "    "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
